package com.mdp.im.core.publish.service;

import com.alibaba.fastjson.JSONObject;
import com.mdp.core.api.Sequence;
import com.mdp.core.err.BizException;
import com.mdp.im.core.plugin.api.PublishPlugin;
import com.mdp.im.core.publish.api.action.PublishAction;
import com.mdp.im.core.publish.action.PublishActionFactory;
import com.mdp.im.core.publish.api.service.PublishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ImPublishServiceImpl implements PublishService {
	 
	@Autowired
	Sequence sequenceService;
	
	@Autowired
	PublishActionFactory pushActionFactory;

	@Autowired(required = false)
	List<PublishPlugin> plugins;


	@Override
	public void publishMessage(JSONObject message) {
		boolean go=true;
		if(plugins!=null && plugins.size()>0){
			for (int i = 0; i < plugins.size(); i++) {
				if(go){
					go = plugins.get(i).beforePublish(message);
				} else if(go==false){
					plugins.get(i).beforePublish(message);
				}
			}
		}
		if(go){
			String action=message.getString("action");
			String msgId=message.getString("msgId");
			if(StringUtils.isEmpty(msgId)) {
				msgId= sequenceService.getTablePK("message", "msgId");
				message.put("msgId",msgId);
			}
			PublishAction publishAction = pushActionFactory.getPushAction(action);
			if(publishAction == null) {
				throw new BizException("Invalid action, " + action);
			}
			publishAction.doAction(message);
		}

		if(plugins!=null && plugins.size()>0) {
			for (int i = 0; i < plugins.size(); i++) {
				plugins.get(i).afterPublish(go, message);
			}
		}
	}
}
